/*
 * Copyright (C) 2011, EADS France
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 */
package xowl.gmi.environment;

import xowl.gmi.view.IconProvider;

/**
 *
 * @author Laurent WOUTERS
 */
public class DiagramController implements xowl.gmi.view.DiagramNode.Actions {
    private ProjectController parent;
    private xowl.gmi.model.Diagram model;
    private xowl.gmi.view.DiagramNode view;
    private xowl.gmi.controller.Controller child;
    
    public xowl.utils.logging.Logger getLog() { return parent.getLog(); }
    public Options getOptions() { return parent.getOptions(); }
    public Locale getLocale() { return parent.getLocale(); }
    public xowl.interpreter.Repository getRepository() { return parent.getRepository(); }
    public xowl.gmi.model.Diagram getModel() { return model; }
    public xowl.gmi.view.DiagramNode getViewNode() { return view; }
    public xowl.gmi.view.DiagramView getViewContent() { return child.getView(); }
    public String getTitle() { return model.getName(); }
    
    public DiagramController(ProjectController parent, xowl.gmi.model.Diagram model) {
        this.parent = parent;
        this.model = model;
        this.view = new xowl.gmi.view.DiagramNode(this, parent.getLocale(), model.getName(), model.getWBView().getName());
    }

    @Override public void onOpen() {
        if (child != null)
            return;
        child = xowl.gmi.controller.Controller.newController(parent.getLog(), parent.getOntology(), this);
        parent.openDiagram(this);
    }
    
    @Override public void onDelete() {
        int res = parent.showConfirm(parent.getLocale().diagramDelete.replace("{1}", model.getName()), false);
        if (res == javax.swing.JOptionPane.NO_OPTION)
            return;
        parent.closeDiagram(this);
        child.cleanup();
        child = null;
        parent.removeDiagram(this);
    }
    
    public void onModify() {
        parent.onDiagramModify();
        view.setModified(true);
    }
    
    public void onSave() {
        if (child != null)
            child.save();
        view.setModified(false);
    }
    
    public void onClose() {
        if (child == null)
            return;
        parent.closeDiagram(this);
        child.cleanup();
        child = null;
    }
    
    public void onRemoved() {
        child.cleanup();
        child = null;
    }
    
    public void executeUIAction(UIAction action) {
        parent.executeUIAction(action);
    }
    
    public void execute(xowl.lang.owl2.IRI object, String eeid) { parent.executeOnObject(object, model.getWBView().getExecEntry(eeid)); }
    
    public void onEditCut() { if (child != null) child.onEditCut(); }
    public void onEditCopy() { if (child != null) child.onEditCopy(); }
    public void onEditPaste() { if (child != null) child.onEditPaste(); }
    public void onEditRemove() { if (child != null) child.onEditRemove(); }
    public void onEditDelete() { if (child != null) child.onEditDelete(); }
    
    public void export(String directory, ExportFormat format) throws java.io.IOException {
        String fileName = parent.toString() + " - " + getTitle() + "." + format.toString();
        if (format == ExportFormat.bmp) exportBMP(directory + java.io.File.separator + fileName);
        else if (format == ExportFormat.png) exportPNG(directory + java.io.File.separator + fileName);
        else if (format == ExportFormat.svg) exportSVG(directory + java.io.File.separator + fileName);
    }
    
    private void exportBMP(String file) throws java.io.IOException {
        java.awt.image.BufferedImage image = null;
        if (child != null) {
            image = child.exportBMP();
        } else {
            child = xowl.gmi.controller.Controller.newController(parent.getLog(), parent.getOntology(), this);
            image = child.exportBMP();
            child.cleanup();
            child = null;
        }
        java.io.File outputfile = new java.io.File(file);
        java.lang.System.out.println(outputfile);
        javax.imageio.ImageIO.write(image, "bmp", outputfile);
    }
    private void exportPNG(String file) throws java.io.IOException {
        java.awt.image.BufferedImage image = null;
        if (child != null) {
            image = child.exportBMP();
        } else {
            child = xowl.gmi.controller.Controller.newController(parent.getLog(), parent.getOntology(), this);
            image = child.exportBMP();
            child.cleanup();
            child = null;
        }
        java.io.File outputfile = new java.io.File(file);
        java.lang.System.out.println(outputfile);
        javax.imageio.ImageIO.write(image, "png", outputfile);
    }
    private void exportSVG(String file) throws java.io.IOException {
        org.w3c.dom.Document doc = null;
        if (child != null) {
            doc = child.exportSVG();
        } else {
            child = xowl.gmi.controller.Controller.newController(parent.getLog(), parent.getOntology(), this);
            doc = child.exportSVG();
            child.cleanup();
            child = null;
        }
        
        org.w3c.dom.Node dic = doc.getChildNodes().item(0).getChildNodes().item(0);
        if ("Resources".equals(dic.getNodeName())) {
            // export images
            String dir = (new java.io.File(file)).getParent();
            if (dir == null) dir = ".";
            for (int i=0; i!=dic.getChildNodes().getLength(); i++) {
                org.w3c.dom.Element item = (org.w3c.dom.Element)dic.getChildNodes().item(i);
                String name = dir + "/" + item.getAttribute("name");
                String hash = item.getAttribute("hash");
                javax.swing.ImageIcon icon = IconProvider.getExternalByHash(hash);
                java.io.File outputfile = new java.io.File(name);
                java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(icon.getIconWidth(), icon.getIconHeight(), java.awt.image.BufferedImage.TYPE_3BYTE_BGR);
                java.awt.Graphics2D g2d = image.createGraphics();
                g2d.drawImage(icon.getImage(), 0, 0, icon.getImageObserver());
                javax.imageio.ImageIO.write(image, "png", outputfile);
            }
            doc.getChildNodes().item(0).removeChild(dic);
        }
        
        try (java.io.Writer writer = xowl.utils.Files.getWriter(file)) {
            org.w3c.dom.ls.DOMImplementationLS impl = new org.apache.xerces.dom.DOMImplementationImpl();
            org.w3c.dom.ls.LSOutput output = impl.createLSOutput();
            output.setCharacterStream(writer);
            output.setEncoding("UTF-8");
            org.w3c.dom.ls.LSSerializer serializer = impl.createLSSerializer();
            serializer.write(doc, output);
        }
    }
}
